<template>
    <div class='wrap'>
        <el-row>
            <el-form ref="formRef" :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="姓名" prop="userName">
                    <el-input v-model="formInline.userName" />
                </el-form-item>
                <el-form-item label="学号" prop="account">
                    <el-input v-model="formInline.account" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="formInline.sex" style="width:100px" placeholder="请选择">
                        <el-option label="男" value="男" />
                        <el-option label="女" value="女" />
                    </el-select>
                </el-form-item>
                <el-form-item label="专业" prop="speciality">
                    <el-input v-model="formInline.speciality" />
                </el-form-item>
                <el-form-item label="班级" prop="userClass">
                    <el-input v-model="formInline.userClass" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">查询</el-button>
                    <el-button @click="resetForm(formRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </el-row>

        <el-row>
            <!-- 你的模板内容 -->
            <el-button type="primary" @click="add">新增</el-button>
            <el-button type="primary" :disabled="multipleSelection.length === 0" @click="multiDelete">批量删除</el-button>
        </el-row>
        <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
            class="mt20" empty-text="暂无数据">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="55" />
            <el-table-column label="标题" property="account">
            </el-table-column>
            <el-table-column label="内容" property="userName">
            </el-table-column>
            <el-table-column property="sex" label="应测人数" />

            <el-table-column label="实测人数" property="speciality">
            </el-table-column>
            <el-table-column label="截止日期" property="userClass">
            </el-table-column>

            <el-table-column label="操作" width="120">
                <template #default="scope">
                    <el-button type="primary" link @click="editUser(scope.row)">修改</el-button>
                    <el-button type="danger" link @click="deleteUser(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination layout="sizes,prev, pager, next" :total="pageInfo.total" @current-change="currentChange"
            @size-change="sizeChange" :page-sizes="[10, 20, 30, 40, 50, 100]" />
        <el-dialog v-model="dialogVisible" :title="handleType === 'add' ? '新增人员' : '编辑人员'" width="500">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="姓名" prop="userName">
                    <el-input v-model="ruleForm.userName" />
                </el-form-item>
                <el-form-item label="学号" prop="account">
                    <el-input v-model="ruleForm.account" />
                </el-form-item>
                <el-form-item label="初始密码" prop="password">
                    <el-input v-model="ruleForm.password" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="ruleForm.sex" style="width:100px" placeholder="请选择">
                        <el-option label="男" value="男" />
                        <el-option label="女" value="女" />
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="ruleForm.phone" type="number" />
                </el-form-item>
                <el-form-item label="专业" prop="speciality">
                    <el-input v-model="ruleForm.speciality" />
                </el-form-item>
                <el-form-item label="班级" prop="userClass">
                    <el-input v-model="ruleForm.userClass" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submit">提交</el-button>
                    <el-button @click="dialogVisible = false">
                        关闭
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>


<script setup>
import { useRouter, useRoute } from 'vue-router';
import { ref, reactive, watch, inject } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
const request = inject('request')
const router = useRouter();
const route = useRoute();
const formInline = ref({})
const formRef = ref()
const handleType = ref('add')
const dialogVisible = ref(false)
const ruleFormRef = ref(null)
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    pageInfo.value.pageNum = 1
    pageInfo.value.pageSize = 10
    getUserList()
}
const onSubmit = () => {
    pageInfo.value.pageNum = 1
    pageInfo.value.pageSize = 10
    getUserList()
}
const currentChange = (val) => {
    pageInfo.value.pageNum = val
    getUserList()
}
const sizeChange = (val) => {
    pageInfo.value.pageSize = val
    getUserList()
}
const pageUserType = 'student'  ///teacher  student
const multipleTableRef = ref()
const multipleSelection = ref([])
const toggleSelection = (rows) => {
    if (rows) {
        rows.forEach((row) => {
            multipleTableRef.value.toggleRowSelection(row, undefined)
        })
    } else {
        multipleTableRef.value.clearSelection()
    }
}
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}

// 数据列表
const tableData = ref([])
const pageInfo = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
})
const getUserList = async () => {
    const res = await request.post('user/userList', {
        type: pageUserType,
        ...formInline.value,
        ...pageInfo.value
    });
    if (res.code === 200) {
        tableData.value = res.data.list
        pageInfo.value = {
            pageNum: res.data.pageNum,
            pageSize: res.data.pageSize,
            total: res.data.total
        }
    }
}
getUserList()

// 新增编辑弹窗
const rules = {
    userName: [
        { required: true, message: '请输入内容', trigger: 'blur' },
    ],
    account: [
        { required: true, message: '请输入内容', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入内容', trigger: 'blur' },
    ],
    sex: [
        { required: true, message: '请输入内容', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '请输入内容', trigger: 'blur' },
    ],
    userClass: [
        { required: true, message: '请输入内容', trigger: 'blur' },
    ],
    speciality: [
        { required: true, message: '请输入内容', trigger: 'blur' },
    ],
}
const ruleForm = ref({})


const submit = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            let url = handleType.value === 'add' ? 'user/addUser' : 'user/updateUser'
            console.log(url);
            const res = await request.post(url, { ...ruleForm.value, type: pageUserType });
            if (res.code === 200) {
                ElMessage.success('提交成功')
                dialogVisible.value = false
                getUserList()
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

const add = () => {
    dialogVisible.value = true;
    handleType.value = 'add'
}

const editUser = (row) => {
    ruleForm.value = row
    dialogVisible.value = true
    handleType.value = 'edit'

}
const multiDelete = () => {
    ElMessageBox.confirm(
        `确认批量删除${multipleSelection.value.length}条数据吗？`,
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let url = 'user/batchDelUser'
            let ids = multipleSelection.value.map(item => item.userId)
            const res = await request.post(url, { ids });
            if (res.code === 200) {
                ElMessage.success('删除成功')
                dialogVisible.value = false
                getUserList()
            }

        })
}
const deleteUser = (row) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let url = 'user/delUser'
            const res = await request.get(url + '?userId=' + row.userId);
            if (res.code === 200) {
                ElMessage.success('删除成功')
                dialogVisible.value = false
                getUserList()
            }

        })


}
watch(dialogVisible, (val) => {
    if (!val) {
        ruleFormRef.value.resetFields()
        handleType.value = 'add'
    }
})
</script>


<style scoped lang="scss">
.wrap {
    background-color: #fff;
    padding: 20px;
    border-radius: 10px;
    margin: 10px auto;
}

.example-pagination-block+.example-pagination-block {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 20px;
}
</style>